<template>
  <div class="flex-container">
    <div id="course-menu">
      <Menu ref="sideMenu" active-name="abstract" @on-select="loadContent">
        <MenuItem name="abstract">课程概览</MenuItem>
        <Submenu v-for="chapter in catalog" :name="chapter.id" :key="chapter.id">
          <template slot="title">{{chapter.title}}</template>
          <MenuItem v-for="section in chapter.children"
          :name="section.id" :key="section.id">{{section.title}}</MenuItem>
        </Submenu>
      </Menu>
    </div>
    <div class="flex-container">
      <div id="course-content">
        <CourseAbstract v-if="courseOverview"></CourseAbstract>
        <Panel v-if="sectionContent">
          <div class="sectionVideo">
            <Tabs type="card" :animated="false" v-model="editableTabsValue" @on-click="handleClick()">
              <Tab-pane
                v-for="(item) in editableTabs"
                :key="item.name"
                :label="item.label"
                :name="item.name"
                :id="item.name" style="margin-bottom:50px;">
                <div class="videoExample" v-if="item.label === '视频'">
                  <p class="resourceTitle">{{item.content}}</p>
                  <video controls="controls" preload="auto" :id="item.id" :src="item.url">
                    当前浏览器不支持video直接播放，推荐使用Chrome浏览器进行播放
                  </video>
                </div>
                <div v-if="item.label === 'PPT'">
                  <p class="resourceTitle">{{item.content}}</p>
                  <iframe
                  id="previewPDF" :src="item.url" :download="item.content">
                  </iframe>
                </div>
                <div v-if="item.label === '作业' && homeworkVisible">
                  <Homework :taskData="task" :key="time" v-if="refresh"/>
                </div>
              </Tab-pane>
            </Tabs>
          </div>
        </Panel>
        <Panel v-if="noResources">
          <div class="noResources">
            当前节课程资源还未上传，请先学习其他章节的资源吧~
          </div>
        </Panel>
      </div>
    </div>
  </div>
</template>

<script>
import api from '@oj/api'
import CourseAbstract from './children/CourseAbstract'
import Homework from './children/Homework'

export default {
  components: {
    CourseAbstract, Homework
  },
  data () {
    return {
      catalog: null,
      courseOverview: true,
      sectionContent: false,
      time: new Date().getTime(),
      noResources: false,
      editableTabs: [], // 加载对应节的资源
      editableTabsValue: '', // 默认显示tab的名称
      resources: [],
      task: {
        'sectionId': '',
        'paper': {},
        'paperDetail': [],
        'paperDetailProblems': []
      },
      refresh: true,
      homeworkVisible: true, // true可以看到作业，false看不到作业
      lastBrowseLocation: null,
      progress: 0
    }
  },
  mounted () {
    // baseurl
    const env = process.env
    this.baseUrl = env.baseUrl + '/api/course/section?path='
    // 请求左侧章节数据
    api.getChapters(this.$route.params.courseId).then(res => {
      let chapters = res.data.data
      let tempctlg = {}
      chapters.forEach(chapter => {
        chapter.children = []
        tempctlg[chapter.id] = chapter
      })
      api.getSections(this.$route.params.courseId).then(res => {
        let sections = res.data.data.reverse()
        sections.forEach(section => {
          tempctlg[section.chapter.id].children.push(section)
        })
        this.catalog = Object.values(tempctlg)
      })
    })
    if (!this.$route.params.classroomId) {
      // 没有classroomid，仅浏览课程，作业不显示
      this.homeworkVisible = false
    }
  },
  methods: {
    async loadContent () {
      let sectionId = this.$refs.sideMenu.currentActiveName
      // 判断是否是课程概览页面
      if (sectionId !== 'abstract') {
        this.courseOverview = false
        // 点击的是节
        this.editableTabs = [] // 重置页面tab数据
        let name = 1
        // 请求课程资源 (视频资源没有video的id)
        await api.getSectionResources(sectionId).then(res => {
          res.data.data.forEach(e => {
            // 判断资源类型，添加对应类型的资源
            if (e.genre === 'video') {
              this.editableTabs.push({
                label: '视频',
                name: '视频' + e.id,
                id: 'lecture' + e.id,
                content: e.title,
                url: this.baseUrl + e.url})
            } else if (e.genre === 'pdf') {
              this.editableTabs.push({
                label: 'PPT',
                name: name.toString(),
                content: e.title,
                url: this.baseUrl + e.url})
            }
            name++
          })
        })
        // 作业可显示时，请求作业数据
        if (this.homeworkVisible) {
          // 请求作业数据
          await api.getSectionHomeworks(sectionId).then(res => {
            res.data.data.forEach(e => {
              this.editableTabs.push({
                label: '作业',
                name: '作业' + e.id,
                content: e.title})
            })
          })
        }
        if (this.editableTabs.length) {
          // 该节下有课程资源
          this.editableTabsValue = this.editableTabs[0].name // 显示该节下第一个课程资源
          this.sectionContent = true
          this.noResources = false
        } else {
          // 显示没有资源页面
          this.sectionContent = false
          this.noResources = true
        }
      } else {
        // 显示课程概览
        this.courseOverview = true
        this.sectionContent = false
        this.noResources = false
      }
      // 默认显示的tab是视频时，添加eventListener，settimeout防止页面未加载就添加eventlistener
      setTimeout(() => {
        this.handleClick()
      }, 500)
    },
    handleClick () {
      let tabname = this.editableTabsValue
      if (tabname.substr(0, 2) === '作业') {
        let homeworkid = this.editableTabsValue.slice(2)
        this.loadHomework(homeworkid)
      }
      // classroom下的视频观看记录处理
      if (tabname.substr(0, 2) === '视频' && this.$route.params.classroomId) {
        // 获取学生观看视频的记录
        let videoId = tabname.substr(2)
        var videoElement = document.getElementById('lecture' + videoId)
        // 清空上个视频的历史记录
        this.lastBrowseLocation = 0
        this.progress = 0
        let created = 0 // 是否有历史记录的flag，创建过=1，未创建过=0
        // 获取视频播放记录
        api.getClassroomStudentVideoProgress(this.$route.params.classroomId, videoId).then(res => {
          if (res.data.data) {
            this.lastBrowseLocation = parseInt(res.data.data.lastBrowseLocation)
            created = this.lastBrowseLocation ? 1 : 0 // 创建过=1，未创建过=0
            this.progress = res.data.data.progress
            // 视频定位， 如果播放完，当前位置设置为视频结尾， 否则设置为上次播放位置
            if (this.lastBrowseLocation === parseInt(videoElement.duration)) {
              videoElement.currentTime = videoElement.duration
            } else {
              videoElement.currentTime = this.lastBrowseLocation
            }
          }
        }).catch(e => {
        })
        // 监听并保存视频进度
        let frequence = 0
        videoElement.addEventListener('timeupdate', () => {
          let currentTime = Math.floor(videoElement.currentTime)
          let videoLength = Math.floor(videoElement.duration)
          frequence++
          // 时间大于0，每隔大约5s（timeupdate每秒调用大概4次，20次约等于5s），向服务器发送请求
          if (currentTime > 0 && frequence === 20) {
            frequence = 0
            // 计算观看视频进度：如果观看完视频，process是100不会改变
            let process = this.progress !== 100 ? Math.floor(currentTime / videoLength * 100) : 100
            let passData = {
              classroom_id: this.$route.params.classroomId,
              video_id: videoId,
              lastBrowseLocation: currentTime,
              progress: process
            }
            if (created) {
              this.updateVideoProgress(passData)
            } else {
              created = 1
              this.createVideoProgress(passData)
            }
          }
          // 切换tab，暂停视频
          if (this.editableTabsValue !== '视频' + videoId) {
            videoElement.pause()
          }
        })
        // 播放结束后事件
        videoElement.addEventListener('ended', () => {
          // 设置progress为100
          this.progress = 100
          let passData = {
            classroom_id: this.$route.params.classroomId,
            video_id: videoId,
            lastBrowseLocation: Math.floor(videoElement.duration),
            progress: 100
          }
          this.updateVideoProgress(passData)
        })
      }
    },
    createVideoProgress (passData) {
      api.postClassroomStudentVideoProgress(passData).then(res => {
        this.lastBrowseLocation = passData.lastBrowseLocation
      })
    },
    updateVideoProgress (passData) {
      api.putClassroomStudentVideoProgress(passData).then(res => {
      })
    },
    async loadHomework (homeworkid) {
      this.task.paperDetail = [] // 重置作业题
      this.task.paperDetailProblems = []
      let submissionStatus = []
      // 请求作业题目的提交情况
      await api.getHomeworkSubmissions(homeworkid, this.$route.params.classroomId).then(res => {
        submissionStatus = res.data.data
      })
      // 请求作业下的全部习题信息
      await api['getHomework'](homeworkid).then(res => {
        // 传递作业数据到homework页面
        this.task.paper.id = res.data.data.homeworkId
        this.task.paper.title = res.data.data.title
        res.data.data.selectionProblems.forEach(e => {
          let submitted = false
          let studentAnswer = ''
          let yourAnswer = 0
          if (e.selectionProblem.selectionProblemType === 'multiple') {
            studentAnswer = []
            yourAnswer = []
          }
          let result = 0
          // 加载本题之前的答题记录信息
          submissionStatus.selectionProblemSubmissions.forEach(element => {
            if (element.selectionProblem === e.selectionProblem.id) {
              submitted = true // 题目已经提交过
              result = element.statistic_info.score
              if (e.selectionProblem.selectionProblemType === 'multiple') {
                yourAnswer = []
                element.info.forEach(i => {
                  i = JSON.parse(i.replace(/'/g, '"'))
                  if (i.result) {
                    yourAnswer.push(i.option)
                  }
                })
                studentAnswer = element.answers
              } else {
                let info = JSON.parse(element.info[0].replace(/'/g, '"'))
                studentAnswer = info.option
                yourAnswer = info.result
              }
            }
          })
          // 添加本题题目信息，答题信息到试卷上
          this.task.paperDetail.push(JSON.parse(JSON.stringify(
            {
              id: e.selectionProblem.id,
              subject: e.selectionProblem.description, // 题目
              options: e.selectionProblem.choices, // 题目选项
              studentAnswer: studentAnswer, // 学生的答案
              studentScore: result, // 学生答案获得的分数
              analysis: '',
              score: parseInt(e.score), // 题目分数
              selection_problem_type: e.selectionProblem.selectionProblemType,
              yourAnswer: yourAnswer, // 答案是否正确,单选判断题为0/1，多选题为选择正确的选项数组
              submitted: submitted // 是否提交
            }
          )))
        })
        if (res.data.data.problems.length) {
          res.data.data.problems.forEach(e => {
            // 找到这道题的全部提交记录
            let submissions = []
            submissionStatus.programProblemSubmissions.forEach(programSubmission => {
              if (programSubmission.problem === e.problem.id) {
                submissions.push(programSubmission)
              }
            })
            let code = ''
            let result = 9
            let submissionExists = false
            let language = ''
            let studentScore = 0
            if (submissions.length) {
              submissionExists = true
              result = { result: submissions[0].result }
              code = submissions[0].code
              language = submissions[0].language
              // 学生分数：OI计算成绩模式下才有score分数，题目满分需要再创建题目时进行设置，默认100分制
              studentScore = Math.round(submissions[0].statistic_info.score / 100 * e.score)  // 以100分制按比例计算所得分数
            }
            this.task.paperDetailProblems.push(JSON.parse(JSON.stringify(
              {
                programmingQuestionId: e.problem.id,
                analysis: '',
                score: Math.round(e.score),
                studentScore: studentScore,
                programmingQuestionInfo: e.problem,
                submissions: submissions, // 以最新数据为最后提交结果
                code: code,
                result: result,
                submissionExists: submissionExists,
                statusVisible: submissionExists,
                language: language,
                submitted: submissionExists
              }
            )))
          })
        }
      })
      this.refresh = false
      this.$nextTick(() => {
        this.refresh = true
      })
    }
  }
}
</script>

<style scoped>
.flex-container #course-menu {
  flex:none;
  width: 246px;
}

.flex-container #course-content {
  flex: auto;
  width: 0;
}

.sectionVideo {
  text-align: center;
}

.videoExample video{
  width: 85%;
  border: 1px solid lightgrey;
  /* margin-top: 20px; */
}

#previewPDF{
  height: 100vh;
  width: 85%;
}

.noResources{
  margin: 0 0 30px 30px;
  text-align: center;
}

.tab-all{
  width: 100%;
}

.ivu-tabs {
  width: 90%;
  margin-left: 30px;
}

.resourceTitle {
  margin: 20px 0;
  font-size: 16px;
}

.ivu-card-head {
  border-bottom-width: 0px;
}
</style>
